<template>
  <div class="map-location-page">
    <h2 style="font-size:2em;font-weight:bold;margin-bottom:20px;">我的实时位置</h2>
    <div id="amap-container" style="width:1800px;height:1000px;max-width:100%;margin:0 auto;border-radius:16px;box-shadow:0 2px 12px #0001;"></div>
    <div v-if="errorMsg" class="error-msg">{{ errorMsg }}</div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'

const errorMsg = ref('')
const amapKey = 'f0bd8437b222d831cf4d06bd7d34beae' // 你的高德key

function loadAmapScript(key) {
  return new Promise((resolve, reject) => {
    if (window.AMap) return resolve()
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}`
    script.onload = resolve
    script.onerror = reject
    document.head.appendChild(script)
  })
}

function initMapWithGeolocation() {
  if (!window.AMap) {
    errorMsg.value = '地图加载失败，请检查网络或API Key'
    return
  }
  const map = new window.AMap.Map('amap-container', {
    zoom: 17,
  })

  // 优先使用浏览器原生定位
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        const lat = pos.coords.latitude
        const lng = pos.coords.longitude
        // 强制用高德 convertFrom 转 GCJ-02
        window.AMap.convertFrom([lng, lat], 'gps', function (status, result) {
          if (status === 'complete' && result.info === 'ok') {
            const gcjLngLat = result.locations[0]
            map.setCenter(gcjLngLat)
            new window.AMap.Marker({
              position: gcjLngLat,
              map,
              title: '我的位置'
            })
          } else {
            // 转换失败 fallback
            map.setCenter([lng, lat])
            new window.AMap.Marker({
              position: [lng, lat],
              map,
              title: '我的位置'
            })
          }
        })
      },
      (err) => {
        // 浏览器定位失败，fallback 到高德自带定位
        map.plugin('AMap.Geolocation', function () {
          const geolocation = new window.AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
            showMarker: true,
            showCircle: true,
            panToLocation: true,
            zoomToAccuracy: true
          })
          map.addControl(geolocation)
          geolocation.getCurrentPosition(function (status, result) {
            if (status === 'complete') {
              // 定位成功后也强制转换
              const lat = result.position.lat
              const lng = result.position.lng
              window.AMap.convertFrom([lng, lat], 'gps', function (status2, result2) {
                if (status2 === 'complete' && result2.info === 'ok') {
                  const gcjLngLat = result2.locations[0]
                  map.setCenter(gcjLngLat)
                  new window.AMap.Marker({
                    position: gcjLngLat,
                    map,
                    title: '我的位置'
                  })
                } else {
                  map.setCenter([lng, lat])
                  new window.AMap.Marker({
                    position: [lng, lat],
                    map,
                    title: '我的位置'
                  })
                }
              })
            } else {
              errorMsg.value = '定位失败：' + result.message
            }
          })
        })
      },
      { enableHighAccuracy: true, timeout: 10000 }
    )
  } else {
    // 不支持浏览器定位，直接用高德自带定位
    map.plugin('AMap.Geolocation', function () {
      const geolocation = new window.AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        showMarker: true,
        showCircle: true,
        panToLocation: true,
        zoomToAccuracy: true
      })
      map.addControl(geolocation)
      geolocation.getCurrentPosition(function (status, result) {
        if (status === 'complete') {
          // 定位成功后也强制转换
          const lat = result.position.lat
          const lng = result.position.lng
          window.AMap.convertFrom([lng, lat], 'gps', function (status2, result2) {
            if (status2 === 'complete' && result2.info === 'ok') {
              const gcjLngLat = result2.locations[0]
              map.setCenter(gcjLngLat)
              new window.AMap.Marker({
                position: gcjLngLat,
                map,
                title: '我的位置'
              })
            } else {
              map.setCenter([lng, lat])
              new window.AMap.Marker({
                position: [lng, lat],
                map,
                title: '我的位置'
              })
            }
          })
        } else {
          errorMsg.value = '定位失败：' + result.message
        }
      })
    })
  }
}

onMounted(async () => {
  try {
    await loadAmapScript(amapKey)
    initMapWithGeolocation()
  } catch (e) {
    errorMsg.value = '地图加载失败，请检查网络或API Key'
  }
})
</script>

<style scoped>
.map-location-page {
  max-width: 1920px;
  margin: 40px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 2px 12px #0001;
  padding: 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.error-msg {
  color: #f56c6c;
  margin-top: 16px;
}
</style> 